const query = require('../utils/DB')
class adModel {
	// 获取广告列表
	static async getAdList(
		nowPage = 1,
		pageSize = 10
	) {
		let start = (nowPage - 1) * pageSize
		let listCount = await query(`select count(*) as num from ad`)
		let list =await query(
			`select a.*,b.pname from ad as a ,ad_position as b where a.pid = b.id limit ${start},${pageSize}`)
		return {
			count: listCount[0].num,
			list: list
		}
	}
	// 获取广告位置列表
	static async getAdPositionList(
		nowPage = 1,
		pageSize = 10
	) {
		let start = (nowPage - 1) * pageSize
		let listCount = await query(`select count(*) as num from ad_position`)
		let list =await query(`select * from ad_position limit ${start},${pageSize}`)
		return {
			count: listCount[0].num,
			list: list
		}
	}
	// 添加广告
	static addAd(name, path, pid) {
		return query(`INSERT INTO ad(name, path, pid) VALUES ('${name}', '${path}', ${pid})`)
	}

	// 添加广告位置
	static addAdPosition(pname, keyword, status) {
		return query(`INSERT INTO ad_position(pname,keyword,status) VALUES ('${pname}', '${keyword}', ${status})`)
	}

	// 修改广告
	static editAd(id, name, path, pid) {
		return query(`UPDATE ad SET pid = ${pid},name='${name}',path='${path}' WHERE id = ${id}`)
	}
	// 需改广告位
	static editAdPosition(id, pname, keyword, status) {
		return query(
			`UPDATE ad_position SET status = ${status},pname='${pname}',keyword='${keyword}' WHERE id = ${id}`)
	}

	// 删除广告
	static delAd(id) {
		return query(`delete from ad where id=${id}`)
	}

	// 删除广告位
	static async delAdPosition(id) {
		let adList = await query(`select * from ad where pid = ${id}`)
		if (adList.length > 0) {
			return false
		} else {
			return query(`delete from ad_position where id = ${id}`)
		}
	}
}
module.exports = adModel